import { _decorator, Component, Node, resources, SpriteFrame, Sprite, UITransform, Layers } from 'cc';
const { ccclass, property } = _decorator;
import Levels from '../../levels'
import { createUINode, randomByRange } from '../../Utils';
import { TileManager } from './TileManager';
import DataManager from '../../Runtime/DataManager';
import ResourceManager from '../../Runtime/ResourceManager';

export const TILE_WIDTH = 55
export const TILE_HEIGHT = 55

@ccclass('TileMapManger')
export class TileMapManger extends Component {
  async init() {
    const { mapInfo } = DataManager.Instance
    const spriteFrames = await ResourceManager.Instance.loadDir('texture/tile/tile')
    DataManager.Instance.tileInfo=[]
    // console.log(spriteFrames);
    for (let i = 0; i < mapInfo.length; ++i) {
      const column = mapInfo[i];
      DataManager.Instance.tileInfo[i]=[]
      for (let j = 0; j < column.length; ++j) {
        const item = column[j];
        if (item.src === null || item.type === null) {
          continue
        }

        //随机瓦片
        let number:number = item.src
        if ((number === 1 || number === 5 || number === 9)&& i%2 === 0 && j%2 === 0) {
          number += randomByRange(0,4)
        }

        const node = createUINode()
        const imgSrc = `tile (${number})`
        const spriteFrame = spriteFrames.find(v => v.name === imgSrc) || spriteFrames[0]
        const tileManager=node.addComponent(TileManager)
        const type=item.type
        tileManager.init(type,spriteFrame,i,j)
        DataManager.Instance.tileInfo[i][j]=tileManager
        node.setParent(this.node)
      }
    }
  }
}
